//
//  CZtiao.swift
//  GZWeibo666
//
//  Created by 刘鋆 on 15/12/1.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

import SVPullToRefresh
import SVProgressHUD


// 统一管理cell的ID
enum CZStatusDetailIdentifier: String {
    case DetailStatusNormalCell = "DetailStatusNormalCell"
    case DetailStatusForwardCell = "DetailStatusForwardCell"
    case DetailCommentCell = "DetailCommentCell"
    case DetailLoadingCell = "DetailLoadingCell"
    case DetailNoDataCell = "DetailNoDataCell"
    
    // 判断返回对应的cellId
    static func cellId(obj: AnyObject) -> String {
        if obj is CZStatus {
            return (obj as! CZStatus).retweeted_status == nil ? DetailStatusNormalCell.rawValue : DetailStatusForwardCell.rawValue
       }
        else if obj is CZPingLunModel {
            return (obj as! CZPingLunModel).loading ? DetailLoadingCell.rawValue : DetailCommentCell.rawValue
        }
        
        return DetailStatusNormalCell.rawValue
    }
}


class CZtiao: UIViewController ,CZStatusBottomViewDelegate{

    
    //微博模型
    private var status: CZStatus
    
    /// 评论模型
    private var comments: [CZPingLunModel] = [CZPingLunModel]()
    
//    private lazy var table: uita
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        title = "微博详情"
        
        prepareUI()
        prepareTableView()
        
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init(status: CZStatus) {
        self.status = status

        super.init(nibName: nil, bundle: nil)
    }

    
    private func prepareUI() {
        
        
//        bottomView.status  = status
        //添加子控件
        view.addSubview(table)
        view.addSubview(bottomView)
        
        //添加约束
         table.translatesAutoresizingMaskIntoConstraints = false
        bottomView.translatesAutoresizingMaskIntoConstraints = false
        
        //table水平
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : table]))

        // bottomView水平
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bv" : bottomView]))
        
        // 垂直方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[tb]-0-[bv(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : table, "bv": bottomView]))
        
        
        
    }
    
    private func prepareTableView() {
        //设置背景
        table.backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        table.estimatedRowHeight = 300
        
        // 注册cell
        table.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailStatusNormalCell.rawValue)
        table.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailStatusForwardCell.rawValue)
        
        table.registerClass(CZDetailCommentCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailCommentCell.rawValue)
        
        table.registerClass(CZDetailLoadingCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailLoadingCell.rawValue)
        
        table.registerClass(CZDetailNoDataCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailNoDataCell.rawValue)
        
        table.dataSource = self
        table.delegate = self
        
        //添加上拉加载更多控件
        table.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loadMoreComment()
        }
    }
    
    /// MACK - 懒加载
    
    ///table
    private lazy var table = UITableView(frame: CGRectZero, style: UITableViewStyle.Plain)
    
    ///headView
    private lazy var detailHeaderView: CZPingLunHeaderView = {
        let view = CZPingLunHeaderView()
        view.delegate = self
        view.status = self.status
        
        return view
    }()
    
    
    ///bottomView
    private lazy var bottomView: CZStatusBottomView = {
       let view = CZStatusBottomView()
        
         view.delegate = self
        return view
    }()
    
    // MARK: - 底部视图代理
    /// 转发按钮点击,弹出转发界面
    func forwardButtonCilck() {
        //model出一个窗口
        let commentVC = CZComposeViewController(controllerType: CZComposeViewControllerType.forward)
        
        //微博模型
        commentVC.status = self.status
        presentViewController(UINavigationController(rootViewController: commentVC), animated: true, completion: nil )
        
    }
    
    //点击评论按钮，弹出评论按钮
    func commentButtonClick() {
        
        let commentVC = CZComposeViewController( controllerType: CZComposeViewControllerType.comment)
        //微博模型
        commentVC.status = self.status
        presentViewController(UINavigationController(rootViewController: commentVC), animated: true, completion: nil )
    }
    
    //点击点赞按钮，就弹出一个框
    func likeButtonClick() {
        SVProgressHUD.showInfoWithStatus("没有开放该窗口")
    }

}

extension CZtiao: CZPingLunHeaderViewDelegate , CZStatusCellDelegate{
    func detailHeaderViewClick(headerView: UIView) {
        
        loadNewComment()
        
        
    }
    
    ///加载最新数据
    private func loadNewComment(){
        
        let since_id = comments.first?.id ?? 0
        
        //添加 正在加载数据的cell
        let loadCommentModel = CZPingLunModel(loading: true)
        comments.insert(loadCommentModel, atIndex: 0)
        
        //重新刷新数据
        table.reloadData()
        
        //滚动到第1组第0个cell
        table.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
        
        CZPingLunModel.loadComment(status.id, since_id: since_id, max_id: 0) { (comments, total_number, previous_cursor, next_cursor, error) -> () in
            //移除正在加载数据的cell
            self.comments.removeFirst()
            
            if error != nil {
//                print("加载最新评论失败: \(error)")
                SVProgressHUD.showErrorWithStatus("加载最新评论失败")
                // 重新刷新数据
                self.table.reloadData()
                return
            }
            
            self.status.comments_count = total_number!
            
            //判断是否加载到数据
            if comments != nil && comments?.count > 0 {
                //将新获取到得数据拼接在现在数据的面前
                self.comments = comments! + self.comments
            }
            
            //重新刷新数据
            self.table.reloadData()
        }
        
    }
    
    ///加载更多数据
    private func loadMoreComment() {
        CZPingLunModel.loadComment(status.id, since_id: 0, max_id: comments.last?.id ?? 0) { (comments, total_number, previous_cursor, next_cursor, error) -> () in
            //停止上拉加载更多动画
            self.table.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                SVProgressHUD.showErrorWithStatus("加载更多评论失败")
                return
            }
            
            self.status.comments_count = total_number!
            
             self.table.showsInfiniteScrolling = next_cursor != 0
            
            //判断是否加载到数据
            if comments != nil && comments?.count > 0 {
                //将新获取到得数据拼接在现有数据
                self.comments = self.comments + comments!
                
                //重新刷新数据
                self.table.reloadData()
            }
        }
    }
    
    /// 点击被转发微博,再弹出一个控制器显示 被转发微博 详情
    func zhuanfaweiboClick(clickStatus: CZStatus) {
        let detailVC = CZtiao(status: clickStatus)
        detailVC.hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(detailVC, animated: true)
    }
    
}




///数据源方法

extension CZtiao: UITableViewDelegate, UITableViewDataSource {
    //显示多少组
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
     //显示多少个
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        } else {
            if comments.count == 0 {
                return 1
            } else {
                //返回 评论数量
                return comments.count
            }
        }
        
    }
    
    // 每个cell的高度
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            let cellId = CZStatusDetailIdentifier.cellId(status)
            
            let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
            
            
            
            let rowHeight = cell.rowHeight(status)
            
            return rowHeight
        }
        else {
            return UITableViewAutomaticDimension
        }
    }
    
    // 显示cell的内容
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
        
            let cellId = CZStatusDetailIdentifier.cellId(status)
            
            let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
            
            //代理
            cell.CellDelegate = self
            
            cell.status = status

            return cell
        }
        else{
            //如果没有数据 显示“还没有人评论”
            if comments.count == 0 {
                //根据重用表示获取对应得cell
                let cell = tableView.dequeueReusableCellWithIdentifier(CZStatusDetailIdentifier.DetailNoDataCell.rawValue) as! CZDetailNoDataCell
                
                cell.message = "还没有人评论"
                
                return cell
            } else {
                //获取评论模型
                let commentModel = comments[indexPath.row]
                
                let cellId = CZStatusDetailIdentifier.cellId(commentModel)
                
                // 根据 重用标示 获取对应的cell
                let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZDetailCommentCell
                
                //给cell设置 评论模型
                cell.model = commentModel
                
                return cell
            }
        }
    
    }
    
    
    /// tableView每组头部视图
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 {   // 第一组显示头部控件
            return detailHeaderView
        } else {    // 其他组没有头部控件
            return nil
        }
    }
    
    /// tableView每组头部高度
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {   // 第一组显示头部控件,高度44
            return 44
        } else {    // 其他组没有头部控件
            return 0
        }
    }
    
    /// tableView每组脚部高度
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {   // 第0组脚部控件高度10
            return 10
        } else {    // // 其他组脚部控件高度0
            return 0
        }
    }
    
    /// tableView是否要高亮
    func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        if indexPath.section == 0 {     // 第0组是微博cell点击的时候不需要高亮
            return false
        } else {    // 其他组显示评论内容,点击cell需要高亮
            return true
        }
    }
    
}
